import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class RedisCacheService {
  private apiBaseUrl = `${environment.apis.default.url}/api/redis`;

  constructor(private http: HttpClient) {}

  /**
   * 获取Redis缓存状态
   */
  getStatus(): Observable<any> {
    return this.http.get<any>(`${this.apiBaseUrl}/status`).pipe(
      catchError(error => {
        console.error('获取Redis状态失败', error);
        return throwError(() => new Error('获取Redis状态失败: ' + (error.message || '未知错误')));
      })
    );
  }

  /**
   * 清除指定模式的缓存
   * @param pattern 缓存键模式
   */
  clearCache(pattern: string): Observable<any> {
    return this.http.post<any>(`${this.apiBaseUrl}/clear`, {}, { params: { pattern } }).pipe(
      tap(result => console.log('缓存清除结果:', result)),
      catchError(error => {
        console.error('清除缓存失败', error);
        return throwError(() => new Error('清除缓存失败: ' + (error.message || '未知错误')));
      })
    );
  }

  /**
   * 预热客户列表缓存
   * @param params 查询参数
   */
  preheatKehuListCache(params: any = {}): Observable<any> {
    return this.http.post<any>(`${this.apiBaseUrl}/preheat-kehu-cache`, params).pipe(
      tap(result => console.log('缓存预热结果:', result)),
      catchError(error => {
        console.error('缓存预热失败', error);
        return throwError(() => new Error('缓存预热失败: ' + (error.message || '未知错误')));
      })
    );
  }

  /**
   * 检查客户列表缓存状态
   */
  getKehuCacheInfo(): Observable<any> {
    return this.http.get<any>(`${this.apiBaseUrl}/kehu-cache-info`).pipe(
      catchError(error => {
        console.error('获取缓存信息失败', error);
        return throwError(() => new Error('获取缓存信息失败: ' + (error.message || '未知错误')));
      })
    );
  }
} 